package edu.unika.aifb.graphindex.importer;

/**
 * Copyright (C) 2009 Lei Zhang (beyondlei at gmail.com)
 * 
 * This file is part of the graphindex project.
 *
 * graphindex is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License, version 2
 * as published by the Free Software Foundation.
 * 
 * graphindex is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with graphindex.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class ImporterRegistry {
	private static ImporterRegistry m_instance;

	private Map<String,String> m_importers;
	private Map<String,String> m_extensions;
	
	static {
		try {
			Class.forName("edu.unika.aifb.graphindex.importer.db.DBImporter");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	private ImporterRegistry() {
		m_importers = new HashMap<String,String>();
		m_extensions = new HashMap<String,String>();
	}
	
	public static ImporterRegistry getInstance() {
		if (m_instance == null)
			m_instance = new ImporterRegistry();
		return m_instance;
	}
	
	public void registerImporter(String type, Class<?> clazz, Collection<String> extensions) {
		registerImporter(type, clazz.getCanonicalName(), extensions);
	}
	
	public void registerImporter(String type, String className, Collection<String> extensions) {
		if (type.contains("."))
			throw new IllegalArgumentException("importer type must not contain '.'");
		m_importers.put(type, className);
		if (extensions != null)
			for (String ext : extensions)
				m_extensions.put(ext, type);
	}
	
	@SuppressWarnings("unchecked")
	private Importer instantiateImporter(String className) {
		if (className == null)
			return null;
		
		try {
			Class<Importer> classDefinition = (Class<Importer>)Class.forName(className);
			return classDefinition.newInstance();
		} 
		catch (InstantiationException e) {
			e.printStackTrace();
		} 
		catch (IllegalAccessException e) {
			e.printStackTrace();
		} 
		catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public Importer getImporter(String type) {
		return instantiateImporter(m_importers.get(type));
	}
	
	public Importer getImporterByClass(String className) {
		return instantiateImporter(className);
	}
	
	public Importer getImporterByExtension(String extension) {
		return getImporter(m_extensions.get(extension));
	}
	
	public String getTypeByExtension(String ext) {
		return m_extensions.get(ext);
	}
}
